﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace NoRefsTest.Client
{
	public class NumericConverter : IValueConverter
	{
		#region IValueConverter Members

		public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var val = Convert(value, targetType, false);
			return val;
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
		{
			var val = Convert(value, targetType, true);
			return val;
		}

		#endregion

		private static object Convert(object value, Type targetType, bool createInstance)
		{
			if (createInstance && value == null && targetType != null) return Activator.CreateInstance(targetType);

			if (value == null || targetType == null || targetType.FullName == typeof (object).FullName) return value;

			var str = value.ToString();
			if (targetType == typeof (double) || targetType == typeof (double?))
			{
				double val;
				if (double.TryParse(str, out val)) return val;
			}
			else if (targetType == typeof (int) || targetType == typeof (int?))
			{
				int val;
				if (int.TryParse(str, out val)) return val;
			}

			return value;
		}
	}
}